import React, { useEffect, useRef, useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";
import { Card } from "@/components/ui/card";

// 设置 workerSrc 为 CDN 路径
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

export default function PDFViewer({ url }: { url: string }) {
  const [numPages, setNumPages] = useState<number | null>(null);
  const [containerWidth, setContainerWidth] = useState<number>(0);
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const updateContainerWidth = () => {
      if (containerRef.current) {
        setContainerWidth(containerRef.current.offsetWidth * 0.9);
      }
    };

    // Initial width calculation
    updateContainerWidth();

    // Listen for window resize
    window.addEventListener("resize", updateContainerWidth);

    // Clean up listener on unmount
    return () => {
      window.removeEventListener("resize", updateContainerWidth);
    };
  }, []);

  return (
    <Card className="overflow-auto h-[75vh] p-4 border-none" ref={containerRef}>
      <Document
        file={url}
        onLoadSuccess={({ numPages }) => setNumPages(numPages)}
        onLoadError={(err) => console.error("PDF Load Error ❌", err)}
      >
        {Array.from(new Array(numPages || 0), (_, index) => (
          <div
            key={`page_${index + 1}`}
            className="relative"
            style={{
              position: "relative",
              width: containerWidth, // Dynamically set the width
              height: "auto",
            }}
          >
            <Page
              pageNumber={index + 1}
              width={containerWidth} // Pass the container's width as the Page width
              loading={"加载中..."} // Display loading message
              renderTextLayer={false} // Disable text layer
              renderAnnotationLayer={false} // Disable annotation layer
            />
            {/* You can add custom overlays, text layer, or image layers here */}
          </div>
        ))}
      </Document>
    </Card>
  );
}
